package controller

import (
	"agent-list---web-development/list/common"
	"agent-list---web-development/list/model"
	"agent-list---web-development/list/response"
	"log"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

func ModifyAvatar(c *gin.Context) {
	DB := common.DB
	account := c.PostForm("account")
	avatar := c.PostForm("avatar")
	a, err := strconv.Atoi(avatar) //将字符串转换为int
	if err != nil {
		response.Response(c, http.StatusBadRequest, 422, nil, "警告，警告！")
		return
	}
	err1 := DB.Exec("UPDATE users SET avatar=? WHERE account=?", a, account).Error
	if err1 != nil {
		log.Println("err:", err1)
		response.Response(c, http.StatusBadRequest, 422, nil, "修改头像失败，请重试！")
		return
	}
	response.Success(c, nil, "修改头像成功！")
}

func ModifyName(c *gin.Context) {
	DB := common.DB
	username := c.PostForm("username")
	account := c.PostForm("account")
	if len(username) > 50 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户名过长！")
		return
	}
	user := model.User{}
	DB.Where("account=? ", account).First(&user)
	if user.UserName == username {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户名与原来相同，请重新输入！")
		return
	}
	err1 := DB.Exec("UPDATE users SET username=? WHERE account=?", username, account).Error
	if err1 != nil {
		log.Println("err:", err1)
		response.Response(c, http.StatusBadRequest, 422, nil, "修改用户名失败，请重试！")
		return
	}
	response.Success(c, nil, "修改用户名成功！")
}

func ModifyPassword(c *gin.Context) {
	DB := common.DB
	password := c.PostForm("password")
	account := c.PostForm("account")

	if len(password) < 6 || len(password) > 12 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "密码长度为6-12位！")
		return
	}
	user := model.User{}
	DB.Where("account=? ", account).First(&user)
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err == nil {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "密码与原来相同，请重新输入！")
		return
	}
	hasedPassword, err2 := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err2 != nil {
		response.Response(c, http.StatusInternalServerError, 500, nil, "加密错误！")
		return
	}
	err1 := DB.Exec("UPDATE users SET password=? WHERE account=?", hasedPassword, account).Error
	if err1 != nil {
		log.Println("err:", err1)
		response.Response(c, http.StatusBadRequest, 422, nil, "修改密码失败，请重试！")
		return
	}
	response.Success(c, nil, "修改密码成功！")
}
